<template>
  <div class="bj_tpTitle">
    <img src="../../img/student/bj_tp@2x.png" class="bj_tp"/>
    <div class="bj_tpTitlepade">
      <div class="bj_tpTitlepadediv">提交作业</div>
      <div class="bj_tpTitlepadeName">字段字段字段字段字段字段</div>
    </div>
  </div>
  <div class="schoolAssignmentCenter">
    <div class="schoolAssignmentTitle">谁谁谁的作业</div>
    <div class="schoolAssignmentfu">视频上传</div>

    <van-uploader v-model="videoList" multiple accept="video/*"  :max-count="3"
                  @click-preview="handleVideoPreview" :before-read="handleBeforeRead" :after-read="handleVideoUpload">
      <template #preview-cover="{ file }">
        <video
          v-if="videoUrls[file.id]"
          :src="videoUrls[file.id]"
          style="width: 120px; height: 120px; object-fit: cover;border: 1px solid #DDDDDD;"
        ></video>

        <div v-if="!isImage(file)" class="play-icon">
          <!-- 使用 Vant 的图标组件 -->
          <van-icon name="play-circle-o" color="white" size="36"/>
        </div>
      </template>
    </van-uploader>
    <div class="player">
      <video-player v-if="showVideoPlay"
                    class="vjs-custom-skin"
                    :options="playerOptions"
                    ref="videoPlayer"
                    @ready="onPlayerReady"
                    @play="onPlayerPlay($event)"
                    @pause="onPlayerPause($event)"
                    @ended="onPlayerEnd($event)"
                    @waiting="onPlayerWaiting($event)"
                    @playing="onPlayerPlaying($event)"
                    @loadeddata="onPlayerLoadeddata($event)"
                    @timeupdate="onPlayerTimeupdate($event)"
                    @statechanged="playerStateChanged($event)"
      ></video-player>
    </div>
  </div>

  <!--  //播放器-->


</template>

<script>
export default {
  setup() {
    const fileList = ref([
      {url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg'},
      // Uploader 根据文件后缀来判断是否为图片文件
      // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
      {url: 'https://cloud-image', isImage: true},
    ]);
    return {
      fileList,
    };
  },
  data() {
    return {
      videoList: [], //upload绑定的数组
      videoUrls: [], // 存储多个视频的URL
      thumbnailUrls: [], // 存储多个视频的缩略图URL
      showVideoPlay: false,
      currentVideoUrl: "", // 当前播放的视频URL
      isPlaying: false,
      currentTime: 0,
      maxTime: 0,
      playerOptions: {
        height: "200px",
        width: "100%",
        playbackRates: [1.0, 2.0], // 可选的播放速度
        autoplay: true,  // 是否自动播放
        controls: true,   // 是否显示控制条
        muted: false, // 默认情况下静音播放
        loop: false, // 是否视频一结束就重新开始
        sources: [
          {
            type: "video/mp4",
            src: ""  // 视频源地址
          }
        ],
        controlBar: {
          currentTimeDisplay: true,
          progressControl: true,  // 是否显示进度条
          playbackRateMenuButton: true, // 是否显示调整播放倍速按钮
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
        poster: "https://your-poster-image.jpg",  // 视频封面
        notSupportedMessage: '此视频暂无法播放，请稍后再试。'  // 不支持播放的消息
        // 其他配置选项...
      }
    };
  },
  methods: {
    isImage(file) {
      // 根据文件扩展名判断是否为图片文件
      const imageExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "webp"];
      const extension = file.name.split(".").pop().toLowerCase();
      return imageExtensions.includes(extension);
    },
    //在读取文件之前执行的函数
    handleBeforeRead(file) {
      console.log(this.videoList)
      file.id = this.videoList.length; //重要！ 获取视频的索引
      if (file.size > 104857600) {
        this.$message.error("选择/录制视频不能超过100M");
        return false;
      }
      return true;
    },

    //处理视频上传
    handleVideoUpload(file) {
      // 创建 FileReader 实例
      const reader = new FileReader();
      // 设置 FileReader 的 onload 事件处理函数，当读取操作完成时触发
      reader.onload = (e) => {
        const videoSrc = e.target.result;
        // 创建一个 video 元素
        const video = document.createElement("video");
        video.src = videoSrc;
        // 设置 video 元素的 loadeddata 事件处理函数
        video.addEventListener("loadeddata", () => {
          // 创建一个 canvas 元素
          const canvas = document.createElement("canvas");
          canvas.width = video.videoWidth;
          canvas.height = video.videoHeight;
          const ctx = canvas.getContext("2d");
          // 将 video 绘制到 canvas 上
          ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
          this.thumbnailUrls.push(canvas.toDataURL("image/png")); // 添加缩略图到数组
          this.videoUrls.push(videoSrc); // 添加视频URL到数组
        });
      };
      //重要!占位符 检查文件类型是否为视频类型，如果不是，则将文件内容添加到视频 URL 数组中
      if (file.file.type && !file.file.type.startsWith("video/")) {
        this.videoUrls.push(file.content);
      }
      reader.readAsDataURL(file.file);
    },
    // 预览视频文件
    handleVideoPreview(file) {
      const type = file.file.type;
      if (type && type.startsWith("video/")) {
        const index = this.videoList.indexOf(file); // 找到当前点击的视频索引
        this.currentVideoUrl = this.videoUrls[index]; // 设置当前播放的视频URL

        this.playerOptions.sources[0].src = this.currentVideoUrl
        this.showVideoPlay = true; // 显示视频播放器的标志
      }
    },
    handleVideodelete(file) {
      // 从 videoList 中移除文件
      // const index = this.videoList.findIndex(item => item.file.id === file.file.id);
      // console.log(index)
      // if (index !== -1) {
      //   URL.revokeObjectURL(this.videoUrls[index]);  // 释放 URL
      //   this.videoUrls.splice(0, 1);
      //   this.videoList.splice(0, 1);
      //
      // }
      // if (index !== -1) {
      //   // 删除 videoUrls 中对应的预览 URL
      //   URL.revokeObjectURL(this.videoUrls[index]);  // 释放 URL
      //   this.videoUrls.splice(index, 1);  // 从 videoUrls 数组中删除对应的 URL
      //   // this.thumbnailUrls.value.splice(videoIndex, 1);
      //   this.thumbnailUrls.splice(index, 1);  // 从 videoUrls 数组中删除对应的 URL
      //
      //   // 从 videoList 中删除对应的文件
      //   this.videoList.splice(index, 1);
      // }
      //
      // console.log(this.thumbnailUrls)
    },

    //播放器
    playOrPause() {
      if (this.isPlaying) {
        this.$refs.videoPlayer.pause();
      } else {
        this.$refs.videoPlayer.play();
      }
    },
    onPlay() {
      this.isPlaying = true;
    },
    onPause() {
      this.isPlaying = false;
    },


    // 准备好了
    onPlayerReady() {
      console.log("准备好了");
    },
    // 视频播放
    onPlayerPlay(player) {
      console.log('播放了');
      console.log(player);
      let playTime = 0;
      if (
        Number(Math.floor(this.playedTime)) ===
        Number(Math.floor(player.duration()))
      ) {
        this.playedTime = 0;
        playTime = 0;
      } else if (
        Number(Math.floor(player.currentTime())) !==
        Number(Math.floor(this.playedTime))
      ) {
        playTime = this.playedTime;
        player.currentTime(playTime)
      }
    },
    // 视频暂停的
    onPlayerPause(player) {
      console.log('暂停中');
      console.log(player);
      this.playedTime = player.currentTime();
    },
    // 视频播放完
    onPlayerEnd(player) {
      console.log('播放结束了');
      console.log(player);
    },
    // DOM元素上的readyState更改导致播放停止
    onPlayerWaiting(player) {
      console.log("播放停止中");
      console.log(player);
    },
    // 视频已开始播放
    onPlayerPlaying(player) {
      console.log("开始播放了");
      console.log(player);
    },
    // 当播放器在当前播放位置下载数据时触发
    onPlayerLoadeddata(player) {
      console.log("开始下载数据");
      console.log(player);
    },
    // 当前播放位置发生变化时触发
    onPlayerTimeupdate(player) {
      console.log("播放位置变化了");
      console.log(player);
      let timeDisplay = player.currentTime();
      if (timeDisplay - this.currentTime > 1) {
        player.currentTime(this.currentTime > this.maxTime ? this.currentTime : this.maxTime);
      }
      this.currentTime = player.currentTime();
      this.maxTime = this.currentTime > this.maxTime ? this.currentTime : this.maxTime;
    },
    //播放状态改变
    playerStateChanged(playerCurrentState) {
      console.log("播放状态变化了");
      console.log(playerCurrentState);
    },
    // 手动暂停视频的播放
    pause() {
      // 视频播放器的方法调用，要使用this.$refs.videoPlayer.player这个对象去调用
      this.$refs.videoPlayer.player.pause()
    }
  },
};
</script>

<style>
.video-preview {
  display: inline-block;
  margin: 5px;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.videoCenterbackpa {
  position: relative;
  width: 100%;
  height: 100%;
}

.videoCenter {
  height: 200px;
}

.vjs-custom-skin {
  width: 94%;
  box-shadow: 1px 2px 3px #ccc;
  margin: 0 auto;
}

.vjs-control-bar {
  background: #0bbbfc !important;
}

.player {
  margin-top: 10px;
}


.bj_tpTitle {
  position: relative;
  z-index: -1;
}

.bj_tp {
  width: 100%;
}

.bj_tpTitlepade {
  position: absolute;
  top: 17px;
  left: 20px;
}

.bj_tpTitlepadediv {
  font-family: PingFangSC, PingFang SC;
  font-weight: 600;
  font-size: 18px;
  color: #FFFFFF;
  line-height: 25px;
  text-align: left;
  font-style: normal;
}

.bj_tpTitlepadeName {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  line-height: 17px;
  text-align: left;
  font-style: normal;
}

.schoolAssignmentCenter {
  padding: 18px 16px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  background: #fff;
  margin-top: -24px;
  z-index: 10;
}

.schoolAssignmentTitle {
  font-family: PingFangSC, PingFang SC;
  font-weight: 600;
  font-size: 16px;
  color: #302E37;
  line-height: 22px;
  text-align: left;
  font-style: normal;
}

.schoolAssignmentfu {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #302E37;
  line-height: 20px;
  text-align: left;
  font-style: normal;
  margin-top: 15px;
  margin-bottom: 8px;
}

.van-uploader__upload {
  width: 103px !important;
  height: 103px !important;
  margin: 0px;
}

.van-uploader__file {
  width: 103px !important;
  height: 103px !important;
}


.van-uploader__preview {
  margin: 0px;
}
</style>
